# receive the segment and store it into db
# return the image standing for result

# receive the data as a series of segments
# use 'id' as the uuid of this data
# use 'sq' as the sequence number
# use 'to' as the total segments
# use 'ct' as the content of this segment
# use 'tzoffset' as the time zone offset
# use 'op' as the operation, default is store segment


import cgi, cgitb
import os, sys



sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))

import utils
from entity import Data
from entity import Segment

from google.appengine.ext import db

from datetime import datetime


  
  


def checkParameter(uuid, seqnum,totalnum):
  # check parameters is not None
  if uuid is None or seqnum is None or totalnum is None:
    print "Location: /static/image/fail.png"
    exit(-1)

  # valid the "seqnum" must be a number
  if not seqnum.isdigit():
    print "Location: /static/image/fail.png"
    exit(-1)
    
  # valid the "totalnum" must be a number
  if not totalnum.isdigit():
    print "Location: /static/image/fail.png"
    exit(-1)

# create segment object & save
def addNewSegment(uuid,seqnum,content):
  segment = Segment(uuid=uuid,seq=int(seqnum),datetime=datetime.utcnow())
  segment.content = db.Text(content, encoding="utf-8")
  segment.put()
  return segment



# =============business logic===============

# get parameters from url

form = cgi.FieldStorage()

uuid = form.getvalue("id")
seqnum = form.getvalue("sq")
totalnum = form.getvalue("to")
content = form.getvalue("ct")

tzoffset = form.getvalue("tzoffset")

op = form.getvalue("op")

# list all segment in db
if op == "list":
  print "Content-Type: text/plain\n"
  for segment in Segment.all():
    print str(segment)
    print "--------------------"

  print "Total:",Segment.all().count()
  exit(0)




# valid url parameter
checkParameter(uuid, seqnum, totalnum)

# add new segment
segment = addNewSegment(uuid,seqnum,content)

# check segment count
results = Segment.all().filter("uuid =",uuid)
count = results.count()
  
  
if count == totalnum:
  data = utils.buildDataById(uuid);
  


# return result status as image

print "Location: /static/image/success.png"



